﻿<%@ WebHandler Language="C#" Class="ShowListBargain" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;
public class ShowListBargain: AjaxHandlerBase
{
    //*******************************************
    //功能概要       ：基本权限初始化设定
    //参数説明       ： 
    //返回值説明     ：-
    //功能詳細       ：-
    //作成者         ：chen.yugong 
    //作成日         ：2010-06-29
    //修改者         ：
    //修改日         ：2010-07-13
    //*******************************************
    private Chenxin.Lib.Business.BLL.ConfirmMainBusinessApply confirmMainBusinessApply  = null;
    
    public ShowListBargain()
    {
        confirmMainBusinessApply = new Chenxin.Lib.Business.BLL.ConfirmMainBusinessApply();
        //签约输入
        htTypePermit.Add("addcontract", Constants.Permit_Addcontract);
        //办证输入
        htTypePermit.Add("addcertificate", Constants.Permit_Addcertificate);
        //成交记录--导出
        htTypePermit.Add("export", Constants.Permit_Bargain_Export);  
    }

    //*******************************************
    //功能概要       ：请求处理
    //参数説明       ：context 请求上下文
    //返回值説明     ：-
    //功能詳細       ：根据请求名 分发请求
    //作成者         ：chen.yugong 
    //作成日         ：2010-06-29
    //修改者         ：
    //修改日         ：2010-07-13
    //*******************************************
    override public void RequestProcess(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strOp = context.Request["op"];
        string strResponse = "";
        string FilePath = Constants.FilePath_Contract;
        
        switch (strOp.ToLower())
        {
            //查询
            case "getlist":
                strResponse = getList(context);
                break;
            //查询
            case "getmodel":
                strResponse = getModel(context);
                break;
            case "getmodel1":
                strResponse = getModel1(context);
                break;
            case "addcontract":
                strResponse = AddContract(context);
                break;
            case "addcertificate":
                strResponse = Addcertificate(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    public string getList(HttpContext context)
    {

        try
        {
            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);
            //查询条件
            string sqlWhere = GenerateCondition(context);
            //排序
            string strOrderField = "a.AddTime desc";
            if (!string.IsNullOrEmpty(context.Request["sort"]))
            {
                strOrderField = context.Request["sort"];
            }
            //查询分页信息
            System.Data.DataSet ds = confirmMainBusinessApply.getContractList(sqlWhere, strPageIndex, strPageSize, strOrderField);
            //总页数
            int count = (int)ds.Tables[1].Rows[0][0];

            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',{2}}}}}", Resources.Message.Global_Msg_SUCCESS, count, JsonHelp.Convert2Json(ds.Tables[0]));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    //*******************************************
    //功能概要       ：查询权限
    //参数説明       ：context 请求上下文
    //返回值説明     ：程序处理信息提示
    //功能詳細       ：生成查询条件语句
    //作成者         ：chen.yugong
    //作成日         ：2010-06-29
    //修改者         ：王玮
    //修改日         ：2010-07-13
    //*******************************************
    public string GenerateCondition(HttpContext context)
    {
        try
        {
            //获取页面查询条件
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            string datetype = context.Request.QueryString["timetype"];
            string starttime = context.Request.QueryString["starttime"];
            string endtime = context.Request.QueryString["endtime"];
            string keyword = context.Request.QueryString["keyword"];
            string businesstype = context.Request.QueryString["showtype"];
            string status = context.Request.QueryString["status"];
            string region = context.Request.QueryString["region"];
            string strLoanType = context.Request["LoanTypeInfo"];

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            
            //判断级联菜单
            if (employee != Guid.Empty)
                sb.AppendFormat(" AND (a.VenderUserId = '{0}' or a.BuyerUserId ='{0}' or (a.ContractId in (select contractid from t_Contract_PointAllotInfo where EmployeeId='{0}'))) ", employee);
            else if (departs != Guid.Empty)
                sb.AppendFormat(" AND (a.VenderDepartId = '{0}' or a.BuyerDepartId ='{0}' or (a.ContractId in (select contractid from t_Contract_PointAllotInfo where DepartId='{0}')))", departs);
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_GetBusDis);

                sb.AppendFormat(" and ((a.VenderDepartId in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%')) or "
                    + "(a.BuyerDepartId in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%')) or "
                    + "(a.ContractId in (select contractid from t_Contract_PointAllotInfo where DepartId in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
                sb.AppendFormat(" and a.BuyerCompanyId = '{0}'", company);
            else if (city != Guid.Empty)
                sb.AppendFormat(" and a.BuyerCityId = '{0}'", city);
            else
                sb.AppendFormat(" and a.BuyerCompanyId = '{0}'", CurrentUserInfo.CompanyId);

            //查询权限判断权限
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewBargaino_All))
            {
                sb1.Append(" (1=1) ");
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewBargain_City))
            {
                sb1.AppendFormat(" (a.BuyerCityId = '{0}')", CurrentUserInfo.CityId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewBargain_Company))
            {
                sb1.AppendFormat(" (a.BuyerCompanyId = '{0}')", CurrentUserInfo.CompanyId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewBargain_Department))
            {
                sb1.AppendFormat(" (EXISTS(Select 1 from t_Business_EmpSetting M WHERE a.VenderDepartId=M.DepartId And M.Userid= '{0}' and SearchContractApply=1)", CurrentUserInfo.UserId.ToString());
                sb1.AppendFormat(" or EXISTS(Select 1 from t_Business_EmpSetting M WHERE a.BuyerDepartId=M.DepartId And M.Userid= '{0}' and SearchContractApply=1)", CurrentUserInfo.UserId.ToString());
                sb1.AppendFormat(" or a.ContractId in (Select ContractId from t_Contract_PointAllotInfo M WHERE EXISTS(select 1 from t_Business_EmpSetting N where M.DepartId=N.DepartId and N.Userid= '{0}' and SearchBargain=1)))", CurrentUserInfo.UserId.ToString());
            }
            else
            {
                sb1.AppendFormat(" (a.VenderUserId = '{0}' or a.BuyerUserId ='{0}' or (a.ContractId in (select contractid from t_Contract_PointAllotInfo where EmployeeId='{0}')))", CurrentUserInfo.UserId);
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());
            
            if (!String.IsNullOrEmpty(starttime))
            {
                sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,a.AddTime,120)),120)  >= '{0}'", (starttime)));
            }
            if (!String.IsNullOrEmpty(endtime))
            {
                sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,a.AddTime,120)),120)  <= '{0}'", (endtime)));
            }
            if (!String.IsNullOrEmpty(keyword))
            {
                sb1.AppendFormat(" and ((a.HouseAddress LIKE '%{0}%') Or(a.ContractCode like '%{0}%'))", keyword);
            }
            if (!String.IsNullOrEmpty(status))
            {
                switch (status.Trim())
                {
                    case "10":
                        sb1.AppendFormat(" and a.status=1");
                        break;
                    case "-1":
                        sb1.AppendFormat(" and a.status=-1");
                        break;
                    default:
                        sb1.AppendFormat(" and (bArchivement={0} AND a.Status = 1) ", status);
                        break;
                }
            }
            if (!String.IsNullOrEmpty(businesstype))
            {
                sb1.Append(string.Format(" and ( a.BusinessType= {0})", businesstype));
            }
            else
            {
                sb1.Append(string.Format(" and ( a.BusinessType= {0})", 10));
            }
            if (!String.IsNullOrEmpty(region))
            {
                sb1.AppendFormat(" and (a.Region LIKE '%{0}%')", region);
            }

            //贷款情况
            if (!String.IsNullOrEmpty(strLoanType))
            {
                switch (strLoanType)
                {
                    case "收件收据贷款":
                        sb1.Append(string.Format(" and b.LoanInfo = '收件收据贷款'"));
                        break;
                    case "普通贷款":
                        sb1.Append(string.Format(" and b.LoanInfo = '普通贷款'"));
                        break;
                    case "转按揭贷款":
                        sb1.Append(string.Format(" and b.LoanInfo = '转按揭贷款'"));
                        break;
                    case "一次性付款":
                        sb1.Append(string.Format(" and b.LoanInfo = '一次性付款'"));
                        break;
                    case "消费贷款":
                        sb1.Append(string.Format(" and b.LoanInfo = '消费贷款'"));
                        break;
                }
            }
            return sb1.ToString();
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
   
     //*******************************************
     //功能概要       ：获得详细信息
     //参数説明       ：context 请求上下文
     //返回值説明     ：程序处理信息提示
     //功能詳細       ：获得详细信息
     //作成者         ：chen.yugong 
     //作成日         ：2010-06-29
     //修改者         ：
     //修改日         ：
     //*******************************************
     public string getModel(HttpContext context)
     {
         try
         {
             string RecordId = context.Request["modelid"];
             Chenxin.Lib.Business.Entity.t_Contract_BaseInfo info = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(new Guid(RecordId));
             if (info == null) {
                 return string.Format("{{success:'1',msg:'{0}',data:''}}", Resources.Message.Msg_Search_NoData);
             }
             Chenxin.Lib.Business.Entity.t_Contract_Infomation info1 = Chenxin.Lib.Business.DAL.t_Contract_Infomation.GetModel(new Guid(RecordId));
             return string.Format("{{success:'1',msg:'成功',data:{{model:{0},model1:{1}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(info), Chenxin.Lib.Utility.JsonHelp.Convert2Json(info1));
         }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
         }
     }

     //*******************************************
     //功能概要       ：获得详细信息
     //参数説明       ：context 请求上下文
     //返回值説明     ：程序处理信息提示
     //功能詳細       ：获得详细信息
     //作成者         ：chen.yugong 
     //作成日         ：2010-06-29
     //修改者         ：
     //修改日         ：
     //*******************************************
     public string getModel1(HttpContext context)
     {
         try
         {
             string RecordId = context.Request["modelid"];
             Chenxin.Lib.Business.Entity.t_Contract_BaseInfo info = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(new Guid(RecordId));
             if (info == null)
             {
                 return string.Format("{{success:'1',msg:'{0}',data:''}}", Resources.Message.Msg_Search_NoData);
             }
             Chenxin.Lib.Business.Entity.t_Contract_Infomation info2 = Chenxin.Lib.Business.DAL.t_Contract_Infomation.GetModel(new Guid(RecordId));
             Chenxin.Lib.Business.Entity.t_Contract_Infomation1 info1 = Chenxin.Lib.Business.DAL.t_Contract_Infomation1.GetModel(new Guid(RecordId));
             return string.Format("{{success:'1',msg:'成功',data:{{model:{0},model1:{1},model2:{2}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(info), Chenxin.Lib.Utility.JsonHelp.Convert2Json(info1), Chenxin.Lib.Utility.JsonHelp.Convert2Json(info2));
         }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
         }
     }
     //*******************************************
     //功能概要       ：添加签约输入
     //参数説明       ：context 请求上下文
     //返回值説明     ：程序处理信息提示
     //功能詳細       ：添加签约输入
     //作成者         ：chen.yugong 
     //作成日         ：2010-06-29
     //修改者         ：
     //修改日         ：
     //*******************************************
     public string AddContract(HttpContext context)
     {
         try
         {
             Chenxin.Lib.Business.Entity.t_Contract_Infomation model = (Chenxin.Lib.Business.Entity.t_Contract_Infomation)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Business.Entity.t_Contract_Infomation));
             if(Chenxin.Lib.Business.DAL.t_Contract_Infomation.Exists(model.ContractId)){
                Chenxin.Lib.Business.Entity.t_Contract_Infomation temp = Chenxin.Lib.Business.DAL.t_Contract_Infomation.GetModel(model.ContractId);
                model.AddTime = temp.AddTime;
                model.AddCityId = temp.AddCityId;
                model.AddCityName = temp.AddCityName;
                model.AddCompanyId = temp.AddCompanyId;
                model.AddCompanyName = temp.AddCompanyName;
                model.AddDepartmentId = temp.AddDepartmentId;
                model.AddDepartmentName = temp.AddDepartmentName;
                model.AddUserId = temp.AddUserId;
                model.AddUserName = temp.AddUserName;
                model.UpdateCityId = CurrentUserInfo.CityId;
                model.UpdateCityName = CurrentUserInfo.CityName;
                model.UpdateCompanyId = CurrentUserInfo.CompanyId;
                model.UpdateCompanyName = CurrentUserInfo.CompanyName;
                model.UpdateDepartmentId = CurrentUserInfo.DepartId;
                model.UpdateDepartmentName = CurrentUserInfo.DepartName;
                model.UpdateUserId = CurrentUserInfo.UserId;
                model.UpdateUserName = CurrentUserInfo.UserName;
                model.UpdateTime = DateTime.Now;
                Chenxin.Lib.Business.DAL.t_Contract_Infomation.Update(model); 
             } else{
                 model.AddTime = DateTime.Now;
                 model.AddCityId = CurrentUserInfo.CityId;
                 model.AddCityName = CurrentUserInfo.CityName;
                 model.AddCompanyId = CurrentUserInfo.CompanyId;
                 model.AddCompanyName = CurrentUserInfo.CompanyName;
                 model.AddDepartmentId = CurrentUserInfo.DepartId;
                 model.AddDepartmentName = CurrentUserInfo.DepartName;
                 model.AddUserId = CurrentUserInfo.UserId;
                 model.AddUserName = CurrentUserInfo.UserName;
                 Chenxin.Lib.Business.DAL.t_Contract_Infomation.Add(model); 
             }
             
             //tianno
             //2010-11-30
             //AddLog
             Chenxin.Lib.Business.Entity.t_Contract_BaseInfo baseinfo = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(model.ContractId);
             string text = CurrentUserInfo.UserName + "：签约输入。成交编号：" + baseinfo.ContractCode;
             AddLog(text, BusinessType.BusinessTypeComboList()["OprType_SignInput"].ToString());
             
             return string.Format("{{success:'1',msg:'{0}',data:''}}", Resources.Message.Global_Msg_SUCCESS);
         }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
         }
     }

     //*******************************************
     //功能概要       ：添加办证输入
     //参数説明       ：context 请求上下文
     //返回值説明     ：程序处理信息提示
     //功能詳細       ：添加办证输入
     //作成者         ：chen.yugong 
     //作成日         ：2010-06-29
     //修改者         ：
     //修改日         ：
     //*******************************************
     public string Addcertificate(HttpContext context)
     {
         try
         {
             Chenxin.Lib.Business.Entity.t_Contract_Infomation1 model = (Chenxin.Lib.Business.Entity.t_Contract_Infomation1)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Business.Entity.t_Contract_Infomation1));
             if (Chenxin.Lib.Business.DAL.t_Contract_Infomation1.Exists(model.ContractId))
             {
                 Chenxin.Lib.Business.Entity.t_Contract_Infomation1 temp = Chenxin.Lib.Business.DAL.t_Contract_Infomation1.GetModel(model.ContractId);
                 model.AddTime = temp.AddTime;
                 model.AddCityId = temp.AddCityId;
                 model.AddCityName = temp.AddCityName;
                 model.AddCompanyId = temp.AddCompanyId;
                 model.AddCompanyName = temp.AddCompanyName;
                 model.AddDepartmentId = temp.AddDepartmentId;
                 model.AddDepartmentName = temp.AddDepartmentName;
                 model.AddUserId = temp.AddUserId;
                 model.AddUserName = temp.AddUserName;
                 model.UpdateCityId = CurrentUserInfo.CityId;
                 model.UpdateCityName = CurrentUserInfo.CityName;
                 model.UpdateCompanyId = CurrentUserInfo.CompanyId;
                 model.UpdateCompanyName = CurrentUserInfo.CompanyName;
                 model.UpdateDepartmentId = CurrentUserInfo.DepartId;
                 model.UpdateDepartmentName = CurrentUserInfo.DepartName;
                 model.UpdateUserId = CurrentUserInfo.UserId;
                 model.UpdateUserName = CurrentUserInfo.UserName;
                 model.UpdateTime = DateTime.Now;
                 Chenxin.Lib.Business.DAL.t_Contract_Infomation1.Update(model);
             }
             else
             {
                 model.AddTime = DateTime.Now;
                 model.AddCityId = CurrentUserInfo.CityId;
                 model.AddCityName = CurrentUserInfo.CityName;
                 model.AddCompanyId = CurrentUserInfo.CompanyId;
                 model.AddCompanyName = CurrentUserInfo.CompanyName;
                 model.AddDepartmentId = CurrentUserInfo.DepartId;
                 model.AddDepartmentName = CurrentUserInfo.DepartName;
                 model.AddUserId = CurrentUserInfo.UserId;
                 model.AddUserName = CurrentUserInfo.UserName;
                 Chenxin.Lib.Business.DAL.t_Contract_Infomation1.Add(model);
             }

             //tianno
             //2010-11-30
             //AddLog
             Chenxin.Lib.Business.Entity.t_Contract_BaseInfo baseinfo = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(model.ContractId);
             string text = CurrentUserInfo.UserName + "：办证输入。成交编号：" + baseinfo.ContractCode;
             AddLog(text, BusinessType.BusinessTypeComboList()["OprType_PaperInput"].ToString());
             
             return string.Format("{{success:'1',msg:'{0}',data:''}}", Resources.Message.Global_Msg_SUCCESS);
         }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
         }
     }
}